package com.kgc.filters;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 登录权限验证过滤器
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    // 设置不拦截白名单
    private List<String> allowTypes = Arrays
            .asList(
                    "/UserLoginServlet",
                    "/AdminLoginServlet",
                    "/CaptchaServlet",
                    "/page/user/userLogin.jsp",
                    "/page/admin/login.jsp");

    // 静态资源白名单 (处理后缀)
    private List<String> staticTypes = Arrays
            .asList(".css", ".js", ".ico", ".png", ".jpg",
                    ".bmp", ".svg", ".less", ".scss", ".json", ".woff", ".otf", ".eot", ".ttf", ".woff2");

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        // 1.放过不拦截白名单
        for (String allowType : allowTypes) {
            if (requestURI.endsWith(allowType)) {
                // 不处理，直接放行
                chain.doFilter(request, response);
                return;
            }
        }
        // 2.放过静态资源
        for (String staticType : staticTypes) {
            if (requestURI.endsWith(staticType)) {
                // 不处理，直接放行
                chain.doFilter(request, response);
                return;
            }
        }
        // 3.判断Session是否存在
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            user = session.getAttribute("admin");
        }
        if (user != null) {
            // 已登录，放行
            chain.doFilter(request, response);
            return;
        }
        // 4.拦截转发到页面
        String page = "/page/admin/login.jsp"; // 默认管理员地址
        if (requestURI.contains("User")||requestURI.contains("user")) {
            page = "/page/user/userLogin.jsp";
        }
        // 5.判断是否是异步请求（ajax）
        String header = request.getHeader("X-Requested-With");
        if ("XMLHttpRequest".equals(header)) {
            // 属于ajax请求
            response.setHeader("sessionstatus", page);
        } else {
            response.setContentType("text/html");
            response.getWriter().println("<script>parent.location.href='" + page + "'</script>");
        }
    }
}
